package com.woniuxy.service.impl;

import com.woniuxy.feign.GoodsFeign;
import com.woniuxy.feign.OrderFeign;
import com.woniuxy.mapper.BidderMapper;
import com.woniuxy.mapper.BiddingRecordMapper;
import com.woniuxy.service.AuctionService;
import com.woniuxy.service.ChatService;
import com.woniuxy.service.NoticeService;
import com.woniuxy.util.TimeUtil;
import com.work.framework.pojo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author kyle
 * @date 2019-09-18 11:57
 */
@Api(value = "AuctionServiceImpl|竞拍业务的实现")
@Service
public class AuctionServiceImpl implements AuctionService {
    @Resource
    private BiddingRecordMapper biddingRecordMapper;
    @Resource
    private BidderMapper bidderMapper;
    @Resource
    private GoodsFeign goodsFeign;
    @Resource
    private OrderFeign orderFeign;
    @Resource
    private ChatService chatService;
    @Resource
    private NoticeService noticeService;
    /**
     * 验证用户是否有竞拍资格
     * @param aid
     * @param uid
     * @return
     */
    @Override
    public ResultDTO verifyUserQualification(Integer aid, Integer uid) {
        //1.验证拍卖是否开始或者结束
        Auction auction = goodsFeign.selectAuction(aid);
        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setCode(500);
        if (auction == null) {
            resultDTO.setMessage("商品竞拍表查询失败");
            return resultDTO;
        }
        //1.2验证拍卖是否已经开始
        Integer status = auction.getStatus();
        if (status != 4) {
            resultDTO.setMessage("不在拍卖期");
            return resultDTO;
        }
        //2.验证是否已经缴纳押金
        Bidder bidder = new Bidder();
        bidder.setUid(uid);
        bidder.setAid(aid);
        Bidder bidders = bidderMapper.findBidder(bidder);
        if (bidders == null) {
            resultDTO.setMessage("没有缴纳押金，请缴纳押金");
            return resultDTO;
        } else if (bidders.getPermission() != 1) {
            resultDTO.setMessage("没有权限");
            return resultDTO;
        }
        resultDTO.setCode(200);
        resultDTO.setMessage("欢迎参加竞拍");
        return resultDTO;
    }

    /**
     * 查询此次竞拍的参与人
     * @param aid
     * @return
     */
    @Override
    public List<Bidder> findBiddersByAid(Integer aid) {
        return bidderMapper.selectBidderByAid(aid);
    }

    /**
     * 缴纳押金获取竞拍资格
     * @param aid
     * @param uid
     * @return
     */
    @Override
    @Transactional
    public ResultDTO insertBidder(Integer aid, Integer uid) {

        //1.验证是拍卖时间，如果在拍卖之前则不冻结押金，在拍卖中则冻结押金
        Auction auction = goodsFeign.selectAuction(aid);
        ResultDTO resultDTO = new ResultDTO();
        if (auction == null) {
            resultDTO.setCode(500);
            resultDTO.setMessage("商品竞拍表查询失败");
            return resultDTO;
        }
        resultDTO.setCode(500);
        //1.1判断是否拍卖结束
        Integer status = auction.getStatus();
        if (status != 3 && status != 4) {
            resultDTO.setMessage("拍卖已经结束，请查看其他的商品");
            return resultDTO;
        }
        //2.判断是否已经缴纳押金
        Bidder bidder = new Bidder();
        bidder.setUid(uid);
        bidder.setAid(aid);
        Bidder bidders = bidderMapper.findBidder(bidder);
        if (bidder == null) {
            resultDTO.setMessage("已经缴纳押金，请不要重复缴纳");
            return resultDTO;
        }
        //3.扣除用户押金
        Integer code = orderFeign.chargeMoney(uid, auction.getCash());
        if (code == null || code == 500) {
            resultDTO.setMessage("扣除用户押金失败");
            return resultDTO;
        }

        //4.插入bidder表
        bidder.setPermission(1);
        String nickName =  ""+ ((char)(Math.random() * 24 + 65))+ (int)Math.random() * 10 + uid;
        bidder.setNickname(nickName);
        bidder.setPledge(auction.getCash());
        //4.1根据商品的状态确定是否冻结用户押金
        if (status == 3) {
            bidder.setpStatus(1);
        } else if (status == 4){
            bidder.setpStatus(0);
        }
        int insert = bidderMapper.insert(bidder);
        if (insert <= 0) {
            resultDTO.setMessage("服务器错误");
            return resultDTO;
        }
        resultDTO.setCode(200);
        resultDTO.setMessage("恭喜缴纳押金成功，获取了拍卖资格");
        return resultDTO;
    }

    /**
     * 查找指定商品的出价记录
     * @param aid
     * @return
     */
    @Override
    public List<BiddingRecord> findBiddingRecord(Integer aid) {
        return biddingRecordMapper.selectBiddingRecords(aid);
    }

    /**
     * 数据库中查找bidder
     * @param bidder
     * @return
     */
    @Override
    public Bidder findBidder(Bidder bidder) {
        return bidderMapper.findBidder(bidder);
    }

    /**
     * 竞拍结束后修改数据
     * @param aid
     * @return
     */
    @Override
    @Transactional
    public Boolean auctionEnd(Integer aid) {
        Auction auction = goodsFeign.selectAuction(aid);
        if (auction == null) {
            return false;
        }
        String stop = auction.getStop();
        String localTime = TimeUtil.getLocalTime();
        Long compare = TimeUtil.compare(stop, localTime);
        if (compare < 0) {
            return false;
        }
        //查询有没有人竞拍
        List<BiddingRecord> biddingRecords = biddingRecordMapper.selectBiddingRecords(aid);
        if (biddingRecords == null || biddingRecords.size() == 0) {
            goodsFeign.updateAuctionStatus(aid,6);
            Bidder bidder = new Bidder();
            bidder.setAid(aid);
            bidder.setpStatus(1);
            bidderMapper.updateBidderByAid(bidder);
            return true;
        }
        //修改商品的状态
        Boolean aBoolean = goodsFeign.updateAuctionStatus(aid, 5);
        if (!aBoolean) {
            return false;
        }
        //查找出价最高的人
        BiddingRecord biddingRecord = null;
        for (int i = biddingRecords.size()-1; i >= 0; i--) {
            biddingRecord = biddingRecords.get(i);
            if (biddingRecord.getStatus() == 1) {
                break;
            }
        }
        if (biddingRecord.getStatus() != 1) {
            return false;
        }
        //解冻竞拍失败的人的押金
        Bidder bidder = new Bidder();
        bidder.setpStatus(1);
        bidder.setAid(aid);
        bidder.setUid(biddingRecord.getUid());
        int isUpdateBidderOk = bidderMapper.updateBidderByAidAndUid(bidder);
        if (isUpdateBidderOk <= 0) {
            return false;
        }
        //修改竞拍记录表信息
        biddingRecord.setStatus(2);
        boolean isUpdateBiddingRecordOk = biddingRecordMapper.updateBiddingRecord(biddingRecord);
        if (!isUpdateBiddingRecordOk) {
            return false;
        }
        //生成订单
        Integer code = orderFeign.addOrder(biddingRecord.getUid(), auction.getGid(), biddingRecord.getPrice());
        if (code == null || code != 200) {
            return false;
        }
        //添加买家和卖家的联系
        GoodsAuctionDTO goodsAuctionDTO = goodsFeign.selectGoodsAndAuctionByAid(aid);
        Chat chat = new Chat();
        UserInfo userInfo = new UserInfo();
        userInfo.setUid(goodsAuctionDTO.getUid());
        chat.setP_uInfo(userInfo);
        userInfo.setUid(biddingRecord.getUid());
        chat.setB_uInfo(userInfo);
        Integer integer = chatService.addChat(chat);

        //发送短信
        Boolean isSuccessOk = noticeService.sendSuccessMessage(biddingRecord.getUid(), auction.getGid());
        if (!isSuccessOk) {
            return false;
        }
        return true;
    }

    @ApiOperation(value = "添加竞拍记录", notes = "添加竞拍记录的商品编号，价格，用户编号")
    @ApiResponse(code = 200,message = "添加成功")
    @Override
    public ResultDTO addBiddingRecord(BiddingRecord biddingRecord) {
        if (null == biddingRecord) {
            return null;
        }
        biddingRecordMapper.updateBiddingRecordByAid(biddingRecord.getAid(), 1, 0);
        boolean result =  biddingRecordMapper.addBiddingRecord(biddingRecord);
        ResultDTO dto = new ResultDTO();
        if (result) {
            dto.setCode(200);
            dto.setMessage("添加成功");
        } else {
            dto.setCode(500);
            dto.setMessage("添加失败");
        }
        return dto;
    }

    @ApiOperation(value = "根据竞拍者用户编号和竞拍编号更新竞拍者出价状态")
    @ApiResponses({
            @ApiResponse(code = 200, message = "更新成功"),
            @ApiResponse(code = 500, message = "更新失败"),
    })
    @Override
    public ResultDTO updateBiddingRecord(BiddingRecord biddingRecord) {
        if (null == biddingRecord) {
            return null;
        }
        boolean result = biddingRecordMapper.updateBiddingRecord(biddingRecord);
        ResultDTO dto = new ResultDTO();
        if (result) {
            dto.setCode(200);
            dto.setMessage("更新成功");
        } else {
            dto.setCode(500);
            dto.setMessage("更新失败");
        }
        return dto;
    }

    @Override
    @ApiOperation(value = "根据竞拍编号查找最高价")
    public ResultDTO findMaxPriceByUidAndAid(BiddingRecord record) {
        if (null == record.getAid()) {
            return null;
        }
        BiddingRecord relRecord = biddingRecordMapper.findMaxPriceByUidAndAid(record);
        ResultDTO dto = new ResultDTO();
        if (null != relRecord) {
            dto.setMessage("发现最高价");
            dto.setCode(200);
            dto.setData(relRecord);
        } else {
            dto.setCode(500);
            dto.setMessage("未找到结果");
        }
        return dto;
    }
}
